#!/bin/sh

rckeymaps='/etc/rc_keymaps/keyes'
triggerhappy='/etc/triggerhappy/triggers.d/example.conf'
kollw_strok=$(sed -n '$=' $rckeymaps)

#  EDIT rckeymaps
#  system("ir-remote rckeymaps '"ircode_star"' '"keyname_star"' '"ircode"' '"keyname"'")
if [ "$1" == "rckeymaps" ]; then
	if [ "$4" == "keyboard" ]; then
		sed -i '/'$2'.'$3'/d' $rckeymaps
#		echo "DELETE rckeymaps 1"
	else
		sed -i '/'$2'.'$3'/d' $rckeymaps
 		echo -e $4" "$5 >> $rckeymaps
		sed -i '/^$/d' $rckeymaps
		echo "EDIT rckeymaps"
	fi

#  EDIT triggerhappy.conf
#  system("ir-remote triggerhappy '"keyname_star"' '"keysost_star"' '"nomerstroki"' '"keyname"' '"keysost"' '"command"'")
elif [ "$1" == "triggerhappy" ]; then
 echo "EDIT triggerhappy.conf "
 sed -i '/\b'$2'\b.'$3'\b/d' $triggerhappy
 echo -e $5'\t'$6'\t'$7 >> $triggerhappy
  sed -i '/^$/d' $rckeymaps

#####

# DELETE rckeymaps
# system("ir-remote rckeymapsdelete '"ircode_star"' '"keyname_star"'")
elif [ "$1" == "rckeymapsdelete" ]; then
 kollw_keyname=$(sed '/\b'$3'\b/!d' $triggerhappy | sed -n '$=')
 if [ "$kollw_keyname" == "1" ]; then
 echo "DELETE rckeymaps "
 #sed -i '/\b'$2'\b.\ \b'$3'\b/d' $rckeymaps
		sed -i '/'$2'.'$3'/d' $rckeymaps
# else
#  echo "NO-DELETE rckeymaps "
 fi

# DELETE triggerhappy.conf
# system("ir-remote triggerhappydelete '"keyname_star"' '"keysost_star"' '"command_star"'")
elif [ "$1" == "triggerhappydelete" ]; then
  echo " DELETE triggerhappy "
 sed -i '/\b'$2'\b.'$3'\b/d' $triggerhappy

#####

#  system("ir-remote rckeymaps_add '"add_nev_ircode"' '"add_nev_keyname"'")
elif [ "$1" == "rckeymaps_add" ]; then
 searh_ircode=$(sed '/\b'$2'\b/!d' $rckeymaps)
 if [ -n "$searh_ircode" ]; then
  echo EXIT saved-ircode!! - The remote control code exists. Check and write another one.
 else
  echo -e "Saved by ircode."
  echo -e $2" "$3 >> $rckeymaps
  sed -i '/^$/d' $rckeymaps
 fi

#  system("ir-remote triggerhappy_add '"keyname_star"' '"keysost_star"' '"command_star"' '"add_nev_keyname"' '"add_nev_keysost"' '"add_nev_command"")
elif [ "$1" == "triggerhappy_add" ]; then
 searh_trgcode=$(sed '/\b'$5'\b\t\b'$6'\b/!d' $triggerhappy)
 if [ -n "$searh_trgcode" ]; then
  echo EXIT!! Button name and state exist. Check and change the name or its state.
 else
  echo -e "Saved by triggerhappy"
  echo -e $5'\t'$6'\t'$7 >> $triggerhappy
  sed -i '/^$/d' $rckeymaps
 fi
fi
